package com.example.client_group5;


import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;
import util.DateUtil;
import util.HttpClientFactory;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;

import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import android.widget.TextView;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;


public class LazyLoading extends Activity{
	int itemsPerPage = 6;
	boolean loadingMore = false;
	boolean loadingHead=false;
	private ArrayList<Tweet> tweets;
	public static UserItemAdapter adapter;
	//private boolean isConnect=false;
	//boolean changeState=false;
	private int max_id = -1;
	private int since_id = -1;
	private PullToRefreshListView listView;;
	
	private View footerView;
	private ImageManager manager;
	private DateUtil dateUtil;
	private LinearLayout lastDetailView=null;
	private RelativeLayout lastView=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.main);
       
        listView = (PullToRefreshListView)findViewById(R.id.ListViewId);
        //Bundle b=getIntent().getExtras();
        dateUtil = new DateUtil();
        tweets = new ArrayList<Tweet>();
   
        manager = ImageManager.getInstance(getApplicationContext());
		//adapter = new ArrayAdapter<Tweet>(this, android.R.layout.simple_list_item_1, tweets);
        adapter = new UserItemAdapter(this, R.layout.listitem, tweets);
        
        //listView.setAdapter(new UserItemAdapter(LazyLoading.this, R.layout.listitem, tweets));
        
        //add the footer before adding the adapter, else the footer will nod load!
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
        listView.addFooterView(footerView);
        listView.setAdapter(adapter);
        //Here is where the magic happens
        listView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				
				Log.d("tag","loading first....");
				Thread thread=new Thread(null,loadFirstListItems);
				thread.start();	
			}
		});
        listView.setOnScrollListener(new OnScrollListener() {
			
        	//useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if(scrollState!=SCROLL_STATE_IDLE&&lastView!=null&&lastDetailView!=null)
				{
					Log.d("tag","destroy lastview when scroll");
					lastDetailView.setVisibility(View.GONE);
					lastView.setVisibility(View.VISIBLE);
				}
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//what is the bottom item that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;				
//				Log.d("tag", "lastInScreen: " + lastInScreen + "/ totalItemCount: " + totalItemCount);
				if((lastInScreen == totalItemCount) && !(loadingMore)){
					Log.d("tag", "Loading more item...........");
					loadingMore = true;
					Thread thread =  new Thread(null, loadMoreListItems);
			        thread.start();
				}
			}
		});
  
        
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg2>=1)
				{
					
				final int position=arg2;
				final LinearLayout tweetDetail = (LinearLayout)arg1.findViewById(R.id.tweet_detail);
				final RelativeLayout tweetView = (RelativeLayout)arg1.findViewById(R.id.tweet_view);
				tweetDetail.setVisibility(View.VISIBLE);
				tweetView.setVisibility(View.GONE);
				if(lastDetailView != null && lastView!=null )
				{
					lastDetailView.setVisibility(View.GONE);
					lastView.setVisibility(View.VISIBLE);
				}
				// Reply
				Button replyBt = (Button)tweetDetail.findViewById(R.id.reply_id);
				replyBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						ArrayList<String> array = new ArrayList<String>();
						Pattern p = Pattern.compile("@(\\w|\\d|-|_){5,15}");
						Matcher result = p.matcher(adapter.getItem(position-1).content);
						while(result.find()){
							array.add(result.group(0));
						}
						String[] replyInfo = new String[3 + array.size()];
						replyInfo[0] = adapter.getItem(position-1).tweet_id;
						replyInfo[1] = adapter.getItem(position-1).username;
						replyInfo[2] = "";
						for(int i = 3; i < array.size() + 3; i ++){
							replyInfo[i] = array.get(i - 3);
						}
						
						Intent i = new Intent(LazyLoading.this, TweetActivity.class);
						Bundle b = new Bundle();
						b.putStringArray("reply", replyInfo);
						i.putExtras(b);
						startActivity(i);						
						
					}
				});
				
				// Delete
		        Button retweetBt = (Button)tweetDetail.findViewById(R.id.retweet_id);
		        LinearLayout deleteLayout = (LinearLayout)tweetDetail.findViewById(R.id.layout_delete_id);
		        
		        Button deleteBt = (Button)tweetDetail.findViewById(R.id.delete_id);
		        UserManager userProfile = SignInActivity.userProfile;
		        int pos=position-1;
		        if(adapter.getItem(position-1).username.equals(userProfile.getUserName("username", ""))){
		        	Log.d("tag","delete layout visible here"+" username:"+
		        			adapter.getItem(position-1).username + "position"+pos);
		        	deleteLayout.setVisibility(View.VISIBLE);
		        	retweetBt.setBackgroundResource(R.drawable.retweet_disable);
		        	retweetBt.setEnabled(false);
		        }
		        else{
		        	deleteLayout.setVisibility(View.GONE);
			        if(adapter.getItem(position-1).isRetweeted){
			        	retweetBt.setBackgroundResource(R.drawable.retweet_bt2);

			        }
		        }
		        
		        // Retweet 
		        retweetBt.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						final String tweet_id = adapter.getItem(position-1).tweet_id;
						if(!adapter.getItem(position-1).isRetweeted){
							AlertDialog alertDialog = new AlertDialog.Builder(LazyLoading.this).create();
							alertDialog.setTitle("Retweet");
							alertDialog.setMessage("Retweet this to your followers?");
							alertDialog.setCancelable(false);
							alertDialog.setButton("Retweet", new DialogInterface.OnClickListener(){	    	
								public void onClick(DialogInterface dialog, int id) {
									new TweetDetail().createRetweet(tweet_id);
									adapter.getItem(position  - 1).isRetweeted = true;
									adapter.notifyDataSetChanged();
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
									return;
								}
							}); 
							alertDialog.setButton3("Quote", new DialogInterface.OnClickListener() {			
								@Override
								public void onClick(DialogInterface dialog, int id) {
									Intent i = new Intent(LazyLoading.this, TweetActivity.class);
									Bundle b = new Bundle();
									String[] value = {"quote", adapter.getItem(position-1).content};
									b.putStringArray("reply", value);
									i.putExtras(b);
									startActivity(i);
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
//									finish();
									return;
								}
							});
							alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
								}
							});
							alertDialog.show();
							
						}
						else{
							AlertDialog alertDialog = new AlertDialog.Builder(LazyLoading.this).create();
							alertDialog.setTitle("Retweet");
							alertDialog.setMessage("Undo this retweet?");
							alertDialog.setCancelable(false);
							alertDialog.setButton("Undo", new DialogInterface.OnClickListener(){	    	
								public void onClick(DialogInterface dialog, int id) {
									new TweetDetail().deleteRetweet(tweet_id);
									adapter.getItem(position - 1).isRetweeted = false;
									adapter.notifyDataSetChanged();
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
									return;
								}
							}); 
							alertDialog.setButton3("Quote", new DialogInterface.OnClickListener() {			
								@Override
								public void onClick(DialogInterface dialog, int id) {
									Intent i = new Intent(LazyLoading.this, TweetActivity.class);
									Bundle b = new Bundle();
									String[] value = {adapter.getItem(position - 1).username, adapter.getItem(position - 1).content};

									b.putStringArray("reply", value);
									i.putExtras(b);
									startActivity(i);
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
//									finish();
									return;
								}
							});
							alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
									tweetDetail.setVisibility(View.GONE);
									tweetView.setVisibility(View.VISIBLE);
								}
							});
							alertDialog.show();					
						}
					
					}
				});
		        
		        //delete
		        deleteBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						AlertDialog alertDialog = new AlertDialog.Builder(LazyLoading.this).create();
						alertDialog.setTitle("Delete");
						alertDialog.setMessage("Do you want to delete this Tweet");
						alertDialog.setCancelable(false);
						alertDialog.setButton("Yes", new DialogInterface.OnClickListener(){	    	
							public void onClick(DialogInterface dialog, int id) {
								Tweet tweet = adapter.getItem(position - 1);
								new TweetDetail().deleteTweet(tweet.tweet_id);
								adapter.remove(tweet);
								adapter.notifyDataSetChanged();
								tweetDetail.setVisibility(View.GONE);
								tweetView.setVisibility(View.VISIBLE);
								return;
							}
						}); 
						alertDialog.setButton2("No", new DialogInterface.OnClickListener() {			
							@Override
							public void onClick(DialogInterface dialog, int id) {
								tweetDetail.setVisibility(View.GONE);
								tweetView.setVisibility(View.VISIBLE);
								dialog.cancel();				
							}
						});
						alertDialog.show();
					}
				});
		        
		        // favorite
		        final Button favoriteBt = (Button)tweetDetail.findViewById(R.id.favorite_id);
		        if(adapter.getItem(position-1).isFavorite){
		        	favoriteBt.setBackgroundResource(R.drawable.favorite_icon2);
		        }
		        favoriteBt.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						String tweet_id = adapter.getItem(position-1).tweet_id;
						if(!adapter.getItem(position-1).isFavorite){
							adapter.getItem(position-1).isFavorite = true;
							new TweetDetail().createFavorite(tweet_id);
							favoriteBt.setBackgroundResource(R.drawable.favorite_icon2);
						}
						else{
							favoriteBt.setBackgroundResource(R.drawable.favorite_icon);
							adapter.getItem(position-1).isFavorite =false;
							new TweetDetail().deleteFavorite(tweet_id);
						}
						adapter.notifyDataSetChanged();
						tweetDetail.setVisibility(View.GONE);
						tweetView.setVisibility(View.VISIBLE);
					}
				});
		     	lastDetailView = tweetDetail;
		     	lastView = tweetView;
		     	if(tweetView.getVisibility()==View.VISIBLE)
		     	{
		     		Tweet tweet=adapter.getItem(position-1);
		     		ImageView icon=(ImageView)tweetView.findViewById(R.id.icon_id);
		     		if(tweet.isRetweeted && !tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_icon1);
						icon.setVisibility(View.VISIBLE);
					}
					if(tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && !tweet.isFavorite){
						icon.setVisibility(View.GONE);
					}
		     	}
				}
				return true;
			}
		});
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(arg2 >= 1){
					Tweet tweet = adapter.getItem(arg2 - 1);
					Log.d("content", tweet.content + " /arg2: " + arg2);
	
//					info[0]: tweet_id, info[1]: fullname, info[2]: username, info[3]: content
//					info[4]: time, info[5]: isRetweeted, info[6]: isFavorite
//					info[7]: retweetedUser, info[8]: user_id, info[9]: image_url, info[10]: img_up_url
					 
					Intent i = new Intent(LazyLoading.this, TweetDetail.class);
					Bundle b = new Bundle();
					String[] info = {tweet.tweet_id, tweet.fullname, tweet.username, tweet.content, tweet.time, "" + tweet.isRetweeted, "" + tweet.isFavorite,
									tweet.retweetedUser, tweet.user_id, tweet.image_url, tweet.img_up_url, "" + (arg2 - 1)};
					b.putStringArray("tweet", info);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
        	
		});
   
    }
    private Runnable loadFirstListItems = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			loadingHead=true;
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			tweets = new ArrayList<Tweet>();
			max_id=-1;
			if(adapter.getCount()>0)
			 since_id = Integer.parseInt(adapter.getItem(0).tweet_id);
			Log.d("tag", "since id: " + since_id);
	    	tweets = getTweets(itemsPerPage);
	    	Log.d("tag", "size of first tweets: " + tweets.size());
//	    	if(tweets.size() > 0){
//	    		since_id= Integer.parseInt(tweets.get(0).tweet_id);
//	    		Log.d("tag", "since id: " + since_id);
//	    	}

			//Done! now continue on the UI thread
	        runOnUiThread(returnResult);
		}
	};
    //Runnable to load the items 
    private Runnable loadMoreListItems = new Runnable() {			
		@Override
		public void run() {
			//Set flag so we cant load new items 2 at the same time
			//loadingMore = true;
	    	try{
	    		Thread.sleep(1000);
	    	}catch(InterruptedException e){}
	    	tweets = new ArrayList<Tweet>();
	    	since_id=-1;
	    	if(adapter.getCount()>0)
	    		max_id = Integer.parseInt(adapter.getItem(adapter.getCount()-1).tweet_id);
    		Log.d("tag", "max id: " + max_id);
	    	tweets = getTweets(itemsPerPage);
	    	Log.d("tag", "size of tweets: " + tweets.size());
//	    	if(tweets.size() > 0){
//	    		//since_id = max_id;
//	    		max_id = Integer.parseInt(tweets.get(tweets.size() - 1).tweet_id);
//	    		Log.d("tag", "max id: " + max_id);
//	    	}
			//Done! now continue on the UI thread
	        runOnUiThread(returnRes);
		}
	};	
	//Since we cant update our UI from a thread this Runnable takes care of that! 
	
	private Runnable returnResult = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(tweets!=null && tweets.size()>0)
			{
				for(int i=0;i<tweets.size();i++)
					adapter.insert(tweets.get(i), 0);
			}
			//Log.d("tag","since_id :"+since_id);
			adapter.notifyDataSetChanged();
			listView.onRefreshComplete();
		}
	};
	
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
        	if(tweets != null && tweets.size() > 0){
        		for(int i = 0; i < tweets.size(); i ++){
        			adapter.add(tweets.get(i));
        		}
        		
        	}
        	Log.d("tag", "Adapter size: " + adapter.getCount());
        	//Update the Application title
        	setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
        	//Tell to the adapter that changes have been made, this will cause the list to refresh
            adapter.notifyDataSetChanged();
			
			//Done loading more.
            if(tweets.size() > 0)
            {	
            	 loadingMore = false;        	
            }
            else
            {
            	listView.removeFooterView(footerView);
            	
            }
        }
    };
    public ArrayList<Tweet> getTweets(int count){
    	String getUrl = "";
    	
    	if(max_id == -1 && since_id==-1)
    		getUrl = Setting.ipServer + "api/tweet/timeline?count=" + count;
    	else if(max_id!=-1)
    		getUrl = Setting.ipServer + "api/tweet/timeline?max_id=" + max_id + "&count=" + count;
    	else if(since_id!=-1)
    		getUrl = Setting.ipServer + "api/tweet/timeline?count=" + count +"&since_id="+since_id;
    	
    	Log.d("tag","url:"+getUrl);
		
    	ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		
		HttpGet get = new HttpGet(getUrl);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
//		    responseBody = SignInActivity.client.execute(get, responseHandler);
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
	
		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		try{
			jsonObject = new JSONObject(responseBody);
			Log.d("tag", jsonObject.toString());
			JSONArray jsonArray = jsonObject.getJSONArray("tweets");
			for(int i = 0; i < jsonArray.length(); i ++){
				JSONObject t = jsonArray.getJSONObject(i);
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
				String img_url = t.getString("img_url").toString();
				String content = t.get("content").toString().trim() + "\n" + img_url;
				boolean isRetweeted = t.getBoolean("is_retweeted");
				boolean isFavorite = t.getBoolean("is_favorite");
				String retweetedUser = t.getString("retweeted_user");
				
				JSONObject author = t.getJSONObject("author");
				
				String user_id = author.get("user_id").toString();
				String username = author.get("username").toString();
				
				String fullname = author.get("fullname").toString();
				String profile_url = author.get("avatar").toString();
				//Log.d("isReweet", "isRetweeted: "+isRetweeted);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id, mention, content, img_url, profile_url, time, isRetweeted, isFavorite, retweetedUser);
				tweets.add(tweet);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return tweets;
	}
	class UserItemAdapter extends ArrayAdapter<Tweet> {
		private ArrayList<Tweet> tweets;
		
		public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tweet> tweets) {
			super(context, textViewResourceId, tweets);
			this.tweets = tweets;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.listitem, null);
			}
			Tweet tweet = tweets.get(position);
			if (tweet != null) {
				TextView fullname = (TextView)v.findViewById(R.id.fullname);
				TextView username = (TextView) v.findViewById(R.id.username);
				TextView mention = (TextView)v.findViewById(R.id.mention);
				TextView message = (TextView) v.findViewById(R.id.content);
				ImageView image = (ImageView) v.findViewById(R.id.avatar);
				ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
				ImageView icon = (ImageView) v.findViewById(R.id.icon_id);
				TextView time = (TextView)v.findViewById(R.id.time_id);
				ImageView retweetIcon = (ImageView)v.findViewById(R.id.retweet_notice_id);
				TextView retweetText = (TextView)v.findViewById(R.id.retweet_user_id);
				if(fullname != null){
					fullname.setText(tweet.fullname);
				}
				if (username != null) {
					username.setText("@" + tweet.username);
				}
				if(mention != null){
					mention.setText(tweet.mention);
				}
				if(message != null) {
					message.setText(tweet.content);
				}
				if(time != null){
					dateUtil.getDiffDate(tweet.time);
					if(dateUtil.getYear() != 0){
						time.setText(dateUtil.getYear() + "y");
					}
					else if(dateUtil.getMonth() != 0){
						time.setText(dateUtil.getYear() + "M");
					}
					else if(dateUtil.getDay() != 0){
						time.setText(dateUtil.getDay() + "d");
					}
					else if(dateUtil.getHour() != 0){
						time.setText(dateUtil.getHour() + "h");
					}
					else if(dateUtil.getMinute() != 0){
						time.setText(dateUtil.getMinute() + "m");
					}
					else if(dateUtil.getSecond() != 0){
						time.setText(dateUtil.getSecond() + "s");
					}
					dateUtil.resetTime();
				}
				if(image != null) {
					image.setTag(tweet.image_url);	
					manager.displayImage(tweet.image_url, LazyLoading.this, image, progressBar);
				}
				if(icon != null){
					if(tweet.isRetweeted && !tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_icon1);
						icon.setVisibility(View.VISIBLE);
					}
					if(tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && !tweet.isFavorite){
						icon.setVisibility(View.GONE);
					}
				}
			if(retweetIcon != null && retweetText != null){
					if(!tweet.retweetedUser.equals("")){
						retweetIcon.setVisibility(View.VISIBLE);
						retweetText.setVisibility(View.VISIBLE);
					    retweetText.setText("Retweeted by " + tweet.retweetedUser);
						
					}
					else{
						retweetIcon.setVisibility(View.GONE);
						retweetText.setVisibility(View.GONE);
					}	
				}

			}
			
			return v;
		}
	}
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			finish();
		}
		return false;
		
	}
    public void onDestroy(){
    	System.gc();
    	super.onDestroy();
    }
   
}
